package com.hmall.item.web;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<String> userIdThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("Authorization");
        if (userId != null) {
            userIdThreadLocal.set(userId);  // 将用户ID保存在 ThreadLocal 中
        }
        return true;
    }

    // 获取用户ID的方法
    public static String getUserId() {
        return userIdThreadLocal.get();
    }

    // 清除ThreadLocal
    public static void clear() {
        userIdThreadLocal.remove();
    }
}
